﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerGames.FarseerPhysics.Dynamics.Joints;
using FarseerGames.FarseerPhysics.Mathematics;

namespace FreeGoo.GameEngine.Renderables.Links
{
    public class SliderJointLink : Link
    {
        public SliderJointLink(ILinkable linkable1, ILinkable linkable2, ILinkable owningLinkable)
            : base(linkable1, linkable2, owningLinkable)
        {
        }

        public SliderJoint SliderJoint { get { return Joint as SliderJoint; } }
        public override Vector2 LinkStart { get { return Linkable1.Body.GetWorldPosition(SliderJoint.Anchor1); } }
        public override Vector2 LinkEnd { get { return Linkable2.Body.GetWorldPosition(SliderJoint.Anchor2); } }
        
        public override float TargetDistance 
        { 
            get 
            { 
                return (SliderJoint.Max + SliderJoint.Min) * 0.5f;
            }

            set 
            {
                float range = SliderJoint.Max - SliderJoint.Min;
                SliderJoint.Min = value - range;
                SliderJoint.Max = value + range;
            }
        }

        public override float DistanceToPoint(Vector2 point)
        {            
            // This isn't 100% accurate, because WorldAnchor refers to the previous timestep, but we'll live with the
            // tiny inaccuracy to save up on some computations...
            return Calculator.DistanceBetweenPointAndLineSegment(point, SliderJoint.WorldAnchor1, SliderJoint.WorldAnchor2);
        }

        protected override void CreateJoint()
        {
            float distance = Vector2.Distance(Linkable1.Position, Linkable2.Position);
            Joint = new SliderJoint(Linkable1.Body, Linkable1.BodyLinkAnchor, Linkable2.Body, Linkable2.BodyLinkAnchor, distance, distance);
            Joint.Tag = this;
        }
    }
}
